<?php

namespace App\Observers;

use App\Models\Reply;
use App\Models\Topic;
use App\Models\User;

// creating, created, updating, updated, saving,
// saved,  deleting, deleted, restoring, restored

class UserObserver
{
    public function saving(User $user)
    {
        // 这样写扩展性更高，只有空的时候才指定默认头像
        if (empty($user->avatar)) {
            $user->avatar = 'https://iocaffcdn.phphub.org/uploads/images/201710/30/1/TrJS40Ey5k.png';
        }
    }

    public function creating(User $user)
    {
        //
    }

    public function updating(User $user)
    {
        //
    }

    public function deleted(User $user)
    {
        $topic = app(Topic::class);
        $topic_ids = $topic->where('user_id', $user->id)->pluck('id')->toArray();

        //1.用户删除时，删除其发布的话题；
        $topic->where('user_id', $user->id)->delete();

        //2. 当用户删除时，删除其发布的回复；
        app(Reply::class)->where('user_id', $user->id)->delete();

        //3.当话题删除时，删除其所属的回复
        app(Reply::class)->whereIn('topic_id', $topic_ids)->delete();

    }
}
